package client

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"task-server-gin/cfg"
	"task-server-gin/model"
)

var db *gorm.DB
var err error

type MysqlTask struct{}

func init() {
	db, err = gorm.Open("mysql", cfg.MYSQL_DST)
	if err != nil {
		fmt.Println("Client init catch error =", err)
	}
}

func InitDB() error {
	db, err = gorm.Open("mysql", cfg.MYSQL_DST)
	if err != nil {
		fmt.Println("InitDB catch error =", err)
		return err
	}
	return nil
}

func (t MysqlTask) GetFresh() *model.GormSingleTask {
	fmt.Println("MysqlTask.GetFresh")
	task := model.GormSingleTask{}
	db.Where(&model.GormSingleTask{State: 101}).First(&task)
	if len(task.Event) > 0 {
		task.State = 102
		go db.Save(&task)
	}
	return &task
}

func (t MysqlTask) UpdateTaskRecord(taskId string) *model.TaskRecord {
	record := model.TaskRecord{}
	db.Where(&model.TaskRecord{TaskId: taskId}).First(&record)

	go func() {
		if record.Release > 0 {
			record.Release = record.Release - 1
			db.Save(&record)
		}
	}()

	return &record
}

func (t MysqlTask) UpdateTaskStateById(jobId string) *model.GormSingleTask {
	fmt.Println("MysqlTask.UpdateTaskStateById")
	task := model.GormSingleTask{}
	db.Where(&model.GormSingleTask{JobId: jobId, State: 102}).First(&task)
	if len(task.Event) > 0 {
		task.State = 103
		go db.Save(&task)
		return &task
	}
	return nil
}

func (t MysqlTask) InsertDownloadRecord(url string) (*model.DownloadRecord, error) {
	if len([]rune(url)) > 50 {
		rs := []rune(url)
		url = string(rs[:50])
	}
	record := model.DownloadRecord{Url: url}
	result := db.Save(&record)
	if result.Error != nil {
		return &record, result.Error
	}
	return &record, result.Error
}

func (t MysqlTask) GetDownloadRecord(url string) (bool, error) {
	if len([]rune(url)) > 50 {
		rs := []rune(url)
		url = string(rs[:50])
	}
	record := model.DownloadRecord{Url: url}
	result := db.Where("url=?", url).First(&record)

	if result.RowsAffected == 0 {
		return true, nil
	}
	return false, result.Error
}

func (t MysqlTask) InsertVideoInfo(item *model.VideoInfo) (bool, error) {
	result := db.Save(&item)
	if result.RowsAffected != 0 {
		// 添加成功
		return true, nil
	}
	return false, result.Error

}

func (t MysqlTask) InsertAuthorInfo(item *model.AuthorInfo) (bool, error) {
	fmt.Printf("InsertAuthorInfo item= %#v", item)
	result := db.Model(&item).Where("author_id = ? and platform = ?", &item.AuthorId, &item.Platform).Update(item)
	if result.RowsAffected != 0 {
		// update success， info update
		fmt.Println("更新成功")
		return true, nil
	} else {
		result = db.Save(&item)
		if result.RowsAffected != 0 {
			// 添加成功
			fmt.Println("创建成功")
			return true, nil
		}
		return false, result.Error
	}
}
